<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品管理</el-breadcrumb-item>
          <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片布局 -->
        <el-card>
          <!--  提示区域 -->
          <el-row>
              <el-col>
                  <el-alert
                    title="注意: 只允许为第三级分类设置相关参数"
                    type="warning"
                    show-icon>
                  </el-alert>
              </el-col>
          </el-row>

          <!-- 选择商品分类 -->
          <el-row>
            <el-col class="cate_flex">
                <span>选择商品分类:</span>
                <!-- 展示商品分类的级联选择器 -->
                <el-cascader
                  v-model="selectKeys"
                  :options="CateList"
                  :props="caccaderConfig"
                  @change="handleChange"
                  clearable>
                </el-cascader>
            </el-col>
          </el-row>

          <!-- 标签区域 动态参数和静态属性 -->
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="动态参数" name="many" :disabled="isUserBtn">
              <el-Button type="primary" :disabled="isUserBtn" @click="showAddParams()">添加参数</el-Button>
              <!-- 动态参数表格数据区域 -->
              <el-table :data="ManyparamsList" style="width: 100%" border stripe>
                <!-- 展开列 -->
                 <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteAttr_vals(scope.row,i)">{{ item }}</el-tag>
                    <!-- 动态编辑按钮(文本框) -->
                    <!-- 文本框 -->
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)">
                    </el-input>
                    <!-- 按钮 -->
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                  </template>
                </el-table-column>

                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column
                  prop="attr_name"
                  label="参数名称"
                  width="680">
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-Button type="primary" icon="el-icon-edit" @click="showCopyReaderParams(scope.row)">编辑</el-Button>
                    <el-Button type="danger" icon="el-icon-delete" @click="deleting(scope.row)">删除</el-Button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only" :disabled="isUserBtn">
              <el-Button type="primary" @click="showAddParams()">添加参数</el-Button>
              <!-- 静态参数表格数据区域 -->
              <el-table :data="OnlyparamsList" style="width: 100%" border stripe>
                <!-- 展开列 -->
                 <el-table-column type="expand">
                   <template slot-scope="scope">
                     <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteAttr_vals(scope.row,i)">{{ item }}</el-tag>
                     <!-- 动态编辑按钮(文本框) -->
                     <!-- 文本框 -->
                     <el-input
                       class="input-new-tag"
                       v-if="scope.row.inputVisible"
                       v-model="scope.row.inputValue"
                       ref="saveTagInput"
                       size="small"
                       @keyup.enter.native="handleInputConfirm(scope.row)"
                       @blur="handleInputConfirm(scope.row)">
                     </el-input>
                     <!-- 按钮 -->
                     <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                   </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column
                  prop="attr_name"
                  label="参数名称"
                  width="680">
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-Button type="primary" icon="el-icon-edit" @click="showCopyReaderParams(scope.row)">编辑</el-Button>
                    <el-Button type="danger" icon="el-icon-delete" @click="deleting(scope.row)">删除</el-Button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
         </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog
          title="添加参数"
          :visible.sync="setAddParamsVisible"
          width="50%">
          <!-- 内容区域 -->
          <!-- 添加参数的表单 -->
          <el-form ref="addParamsFormRef" :model="addParamsForm" :rules="addParamsFormRules" label-width="80px">
            <el-form-item label="参数名称" prop="attr_name">
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部区域 -->
          <span slot="footer">
            <el-button @click="setAddParamsVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams()">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑参数对话框 -->
        <el-dialog
          title="编辑参数"
          :visible.sync="setCopyReaderParamsVisible"
          width="50%">
           <el-form ref="CopyReaderParamsRef" :model="CopyReaderParamsForm" :rules="CopyReaderParamsRules" label-width="80px">
            <el-form-item label="属性名称" prop="attr_name">
              <el-input v-model="CopyReaderParamsForm.attr_name"></el-input>
            </el-form-item>
            <!-- 属性值 -->
            <el-form-item label="属性值" prop="attr_vals">
              <el-input v-model="CopyReaderParamsForm.attr_vals"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="setCopyReaderParamsVisible = false">取 消</el-button>
            <el-button type="primary" @click="CopyReaderParams()">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类的数据
      CateList: [],
      //  级联选择器的配置对象
      caccaderConfig: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //  级联选择器的每次选中的ID值
      selectKeys: [],
      //   标签页每次选中的
      activeName: 'many',
      // 动态参数列表数据
      ManyparamsList: [],
      // 静态态参数列表数据
      OnlyparamsList: [],
      // 添加参数对话框
      setAddParamsVisible: false,
      // 添加参数对话框的参数列表对象
      addParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 添加参数对话框的参数列表验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 编辑参数对话框是否可见
      setCopyReaderParamsVisible: false,
      // 分类ID
      cat_id: 0,
      // 属性ID
      attr_id: 0,
      // 编辑分类信息表单
      CopyReaderParamsForm: {
        attr_name: '',
        attr_sel: '',
        attr_vals: ''
      },
      // 编辑分了信息表单验证规则
      CopyReaderParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ],
        attr_vals: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类的数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.CateList = res.data
    },
    handleChange() {
      this.getParamsList()
    },
    // 获取列表数据
    async getParamsList() {
      // 获取参数列表数据
      const { data: res } = await this.$http.get(`categories/${this.selectKeys[2]}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      // 把每个attr_vals从字符串变为数组 ' '分隔
      res.data.forEach(item => {
        // 如果item的attr_vals为空则返回空数组 防止渲染BUG
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 给每个item绑定自己inputVisible和 inputValue 防止所有展开数据项用同一个
        item.inputVisible = false
        item.inputValue = ''
        item.count = 0
      })
      // 赋值
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      if (this.activeName === 'many') {
        this.ManyparamsList = res.data
      } else {
        this.OnlyparamsList = res.data
      }
      console.log(this.ManyparamsList)
    },
    // 标签页点击的时候
    handleClick() {
      this.getParamsList()
    },
    showAddParams() {
      this.setAddParamsVisible = true
      this.addParamsForm.attr_sel = this.activeName
    },
    // 点击添加参数确定按钮, 添加参数
    addParams() {
      // 进行数据预验证
      this.$refs.addParamsFormRef.validate(valid => {
        if (!valid) return
        // 添加参数
        this.$http.post(`categories/${this.selectKeys[2]}/attributes`, this.addParamsForm).then(res => {
          console.log(res.data)
          if (res.data.meta.status !== 201) return this.$message.error('添加参数失败')
          this.getParamsList()
          this.addParamsForm = []
          this.setAddParamsVisible = false
        })
      })
    },
    // 显示编辑参数对话框
    showCopyReaderParams(row) {
      this.setCopyReaderParamsVisible = true
      this.CopyReaderParamsForm.attr_sel = this.activeName
      // 根据ID值查询参数信息
      this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        params: {
          attr_sel: this.activeName
        }
      }).then(res => {
        if (res.data.meta.status !== 200) return this.$message.error('获取参数信息失败')
        this.CopyReaderParamsForm.attr_name = res.data.data.attr_name
        this.CopyReaderParamsForm.attr_vals = res.data.data.attr_vals
        console.log(this.CopyReaderParamsForm)
      })
      this.cat_id = row.cat_id
      this.attr_id = row.attr_id
    },
    // 点击确认按钮,提交参数
    CopyReaderParams() {
      this.$refs.CopyReaderParamsRef.validate(valid => {
        if (!valid) return
        this.$http.put(`categories/${this.cat_id}/attributes/${this.attr_id}`, this.CopyReaderParamsForm).then(res => {
          console.log(res)
          console.log(this.CopyReaderParamsForm)
          if (res.data.meta.status !== 200) return this.$message.error('更新失败')
          this.$message.success('更新成功')
          this.CopyReaderParamsForm = []
          this.cat_id = 0
          this.attr_id = 0
          this.getParamsList()
          this.setCopyReaderParamsVisible = false
        })
      })
    },
    // 点击删除按钮拿到分类ID和属性ID 并询问是否删除
    async deleting(row) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 删除用户
      this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`).then(res => {
        console.log(res)
        const { data } = res
        if (data.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除参数成功')
        this.getParamsList()
      })
    },
    // 点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true
      row.count = 0
      // 自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 文本框回车和失去焦点时
    handleInputConfirm(row) {
      if (row.count === 0) {
        console.log(row.inputValue)
        if (!row.inputValue) return this.$message.error('属性不能为空')
        row.attr_vals.push(row.inputValue)
        // 又把数组转换成字符串
        console.log(row)
        this.saveAttr_vals(row)
        row.inputVisible = false
        row.inputValue = ''
        row.count = 1
      }
    },
    // 发送编辑提交参数
    saveAttr_vals(row) {
      this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }).then(res => {
        row.attr_vals = res.data.data.attr_vals
        row.attr_vals = row.attr_vals.split(' ')
        if (res.data.meta.status !== 200) return this.$message.error('更新属性失败')
        this.$message.success('更新属性成功')
        console.log(row.attr_vals)
        row.inputVisible = false
        row.inputValue = ''
      })
    },
    // 点击叉叉触发关闭事件
    deleteAttr_vals(row, i) {
      row.attr_vals.splice(i, 1)
      console.log(row)
      this.saveAttr_vals(row)
    }
  },
  computed: {
    //   计算selectKeys数组长度是否为3
    isUserBtn() {
      if (this.selectKeys.length !== 3) {
        console.log(this.selectKeys)
        return true
      } else {
        console.log(this.selectKeys)
        return false
      }
    }
  }
}
</script>

<style lang="less">
  .cate_flex {
    display: flex;
    align-items: center;
    margin-top: 10px;
    .el-cascader {
        margin-left: 7px;
        width: 200px;
    }
  }
  .el-tabs {
    .el-button {
      margin-left: 7px ;
    }
    .el-input {
      margin-left: 5px;
      width: 12%;
  }
}
</style>
